package com.crazy.mybatis.gerenator.service.java;

import java.io.FileWriter;
import java.io.IOException;

import com.crazy.mybatis.gerenator.service.common.Constants;

public class BeanFileWriter {

	private FileWriter fileWriter;

	public BeanFileWriter() {}

	public BeanFileWriter(FileWriter fileWriter) {
		this.fileWriter = fileWriter;
	}

	public FileWriter getFileWriter() {
		return fileWriter;
	}

	public void setFileWriter(FileWriter fileWriter) {
		this.fileWriter = fileWriter;
	}

	public void write(ClassMetaData meta) throws IOException {
		fileWriter.write("package" + Constants.SPACE + meta.getPackageName() + Constants.SEMICOLON);
		println(2);
		for (String clazz : meta.getImportClasses()) {
			fileWriter.write("import" + Constants.SPACE + clazz + Constants.SEMICOLON);
			println();
		}
		println();
		fileWriter.write("public" + Constants.SPACE + meta.getClassType() + Constants.SPACE + meta.getClassName()
				+ Constants.SPACE + Constants.OPEN);
		println(2);
		for (String property : meta.getPropertyList()) {
			intent(1);
			fileWriter.write("private" + Constants.SPACE + meta.getTypeMap().get(property) + Constants.SPACE + property
					+ Constants.SEMICOLON);
			println(2);
		}
		for (String property : meta.getPropertyList()) {
			// setter
			intent(1);
			fileWriter.write("public" + Constants.SPACE + "void" + Constants.SPACE + toSetter(property)
					+ "(" + meta.getTypeMap().get(property) 
					+ Constants.SPACE + property + ")"
					+ Constants.SPACE + Constants.OPEN);
			println();
			intent(2);
			fileWriter.write("this." + property + " = " + property + Constants.SEMICOLON);
			println();
			intent(1);
			fileWriter.write(Constants.CLOSE);
			println(2);
			// getter
			intent(1);
			fileWriter.write("public" + Constants.SPACE + meta.getTypeMap().get(property) + Constants.SPACE + toGetter(property)
					+ "()" + Constants.SPACE + Constants.OPEN);
			println();
			intent(2);
			fileWriter.write("return" + Constants.SPACE + property + Constants.SEMICOLON);
			println();
			intent(1);
			fileWriter.write(Constants.CLOSE);
			println(2);
		}
		fileWriter.write(Constants.CLOSE);
	}

	private void println() throws IOException {
		println(1);
	}

	private void println(int n) throws IOException {
		while (n > 0) {
			n--;
			fileWriter.write(Constants.LINE_END);
		}
	}

	private void intent(int n) throws IOException {
		while (n > 0) {
			n--;
			fileWriter.write(Constants.INTENT);
		}
	}

	private String toSetter(String property) {
		return "set" + upperCaseFirst(property);
	}

	private String toGetter(String property) {
		return "get" + upperCaseFirst(property);
	}

	public String upperCaseFirst(String str) {
		return str.substring(0, 1).toUpperCase() + str.substring(1);
	}
}
